package com.msb.dongbao.common.util;

import cn.hutool.core.map.MapUtil;

import java.util.*;

/**
 * @author: may
 * @date: 2021年05月30日 20:06
 * 签名生成和校验工具类
 */
public class CheckUtils {

    private static String appSecret = "aaa";

    public static boolean checkSign(Map<String, Object> map) {
        String clientSign = map.get("sign").toString();
        //生成签名
        String serverSign = CheckUtils.generatorSign(map);
        //校验
        if (serverSign.equals(clientSign)) {
            return true;
        }
        return false;
    }

    public static String generatorSign(Map<String, Object> map) {
        map.remove("sign");
        //根据map的key排序
        Map<String, Object> sortMap = sortMapByKey(map);
        //转换格式
        Set<Map.Entry<String, Object>> entries = sortMap.entrySet();
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : entries) {
            sb.append(entry.getKey() + "," + entry.getValue() + "#");
        }
        //组装
        sb.append("appSecrec").append(appSecret);
        //生成签名sign
        return MD5Util.md5(sb.toString());
        //return Sha256Utils.getSHA256(sb.toString());
    }

    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (MapUtil.isEmpty(map)) {
            MapUtil.empty();
        }

        Map<String, Object> sortMap = new TreeMap<>(new MyMapComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    private static class MyMapComparator implements Comparator<String> {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    }

    public static void main(String[] args) {
        HashMap<String, Object> map = MapUtil.newHashMap();
        map.put("name", 2);
        map.put("appid", 1);
        //map.put("timestamp", 1622425119681L);
        System.out.println(sortMapByKey(map));

        String generatorSign = generatorSign(map);
        //md5：a78a80cd0704f1fc869665494ef6b87a
        //sha256：667d494188ff09b568e52ee1588243c66b9522b8ce78bf80742e448420b76df1
        System.out.println(generatorSign);
    }
}
